﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;

namespace x264wrapper
{
    class Program
    {
        [DllImport("kernel32.dll")]
        static extern bool AllocConsole();
        public static string GetArg(string cmdline)
        {
            int i;
            bool isinquote = false;
            for (i = 0; i < cmdline.Length; i++)
            {
                if (cmdline[i] == '"') isinquote = !isinquote;
                if (isinquote == true) continue;
                if (cmdline[i] == ' ') break;
            }
            if (i+1 >= cmdline.Length) return "";
            else return cmdline.Substring(i+1);
        }
        static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
            Process p = new Process();
            p.StartInfo.CreateNoWindow = true;
            //p.StartInfo.UseShellExecute = false;
            p.StartInfo.UseShellExecute = true;
            //p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "x264.exe";
            p.StartInfo.Arguments = GetArg(Environment.CommandLine);
            p.Start();
            try
            {
                // Fuck with C#, if you try to put the next line before p.Start(), you will get "No process is associated with this object"
                // If you put it after p.Start(), you may get "Cannot process request because the process has exited"
                p.PriorityClass = ProcessPriorityClass.Idle;
            }
            catch
            {
            }
            //string result = p.StandardOutput.ReadToEnd();
            //AllocConsole();
            //Console.Write(result);
            p.WaitForExit();
        }
    }
}
